package com.hmkj.core.service.wx.impl;

import com.hmkj.common.baseMapper.GenericMapper;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.api.wechat.utils.WechatUtils;
import com.hmkj.core.constant.ConfigNID;
import com.hmkj.core.mapper.wx.WxAccountMapper;
import com.hmkj.core.po.wx.WxAccount;
import com.hmkj.core.service.cache.RedisService;
import com.hmkj.core.service.wx.WxAccountService;
import lombok.extern.log4j.Log4j;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 微信公众号表业务相关Service接口实现<br>
 *
 * @ClassName: WxAccountServiceImpl
 * @author Vector
 * @date   2017-10-18 10:04:13
 */
@Log4j
@Service
@Scope("prototype")
@Transactional(rollbackFor = Exception.class)
public class WxAccountServiceImpl implements WxAccountService {

	@Resource
    private WxAccountMapper wxAccountMapper;
	@Resource
	private RedisService redisService;

    @Override
    public GenericMapper<WxAccount,Integer> _getMapper() {
        return wxAccountMapper;
    }

    @Override
    public String subscribe(Map<String, String> map) {
        log.info("用户关注事件:" + map.toString());
        String forUserName = map.get("FromUserName");
        String toUserName = map.get("ToUserName");
        String inviteCode = map.get("EventKey");
        String msg = "嗨，欢迎关注！\n" +
                "进入i淘刻，淘出“珍”时刻！";
        String baseUri = redisService.get(ConfigNID.WEB_SERVER_URL);
        if (!StringUtils.isBlank(inviteCode) && inviteCode.contains("qrscene_")) {
            // 扫码未关注事件 带邀请码
            inviteCode = inviteCode.substring("qrscene_".length(), inviteCode.length());
            msg += "\n<a href=\"" + baseUri + "api/userRegist/invite?inviteCode=" + inviteCode + "\">点我注册</a>";
        } else if(StringUtils.isNotBlank(inviteCode)){
            // 扫码已关注 带邀请码
            msg = "<a href=\"" + baseUri + "api/userRegist/invite?inviteCode=" + inviteCode + "\">点我注册</a>";
        }
        return WechatUtils.sendTextmessage(forUserName, toUserName, msg);
    }

    @Override
    public boolean checkSignature(String signature, String timestamp, String nonce) {
        return WechatUtils.checkSignature(getWxAccount().getToken(), signature, timestamp, nonce);
    }

    private WxAccount getWxAccount() {
        return wxAccountMapper.selectAll().get(0);
    }
}
